#include <input_manager.h>
#include <transform.h>
#include <utility_math.h>
#include <imgui.h>
#include <imgui_impl_sdl.h>

bool InputManager::pollEvent(float delta) {
    cameraSpeed = 100.0f * delta;
    while (SDL_PollEvent(&mEvent)) {
        ImGui_ImplSDL2_ProcessEvent(&mEvent);
        switch (mEvent.type) {
            case SDL_QUIT:
                return true;
            case SDL_MOUSEMOTION:
                //mouseHandle();
                break;
            case SDL_KEYDOWN:
                keyDownHandle();
                break;
        }
    }
    return false;
}

Mat4x4 InputManager::getViewMat() const {
    return lookAt(camera.position, camera.center, camera.up);
}

void InputManager::mouseHandle() {    
    static constexpr float sensitivity = 0.005f;
    mYaw += sensitivity * (mLastMousePos.x - mEvent.motion.x);
    mPitch += sensitivity * (mEvent.motion.y - mLastMousePos.y);
    mLastMousePos = Vec2f{(float)mEvent.motion.x, (float)mEvent.motion.y};

    if (mPitch > 89.0f) {
        mPitch = 89.0f;
    }
    else if (mPitch < -89.0f) {
        mPitch = -89.0f;
    }

    Vec3f center;
    center.x = cos(radians(mPitch)) * cos(radians(mYaw));
    center.y = sin(radians(mPitch));
    center.z = cos(radians(mPitch)) * sin(radians(mYaw));
    camera.center = normalize(center);
}

void InputManager::keyDownHandle() {
    switch (mEvent.key.keysym.scancode) {
        case SDL_SCANCODE_W:
            camera.move(cameraSpeed * Vec3f{0, 0, -1});
            //camera.position = camera.position + cameraSpeed * Vec3f{0, 0, -1};
            break;
        case SDL_SCANCODE_S:
            camera.move(cameraSpeed * Vec3f{0, 0, 1});
            //camera.position = camera.position + cameraSpeed * Vec3f{0, 0, 1};
            break;
        case SDL_SCANCODE_A:
            camera.move(cameraSpeed * Vec3f{-1, 0, 0});
            //camera.position = camera.position + cameraSpeed * Vec3f{-1, 0, 0};
            break;
        case SDL_SCANCODE_D:
            camera.move(cameraSpeed * Vec3f{1, 0, 0});
            //camera.position = camera.position + cameraSpeed * Vec3f{1, 0, 0};
            break;
        case SDL_SCANCODE_LSHIFT:
            camera.move(cameraSpeed * Vec3f{0, -1, 0});
            //camera.position = camera.position + cameraSpeed * Vec3f{0, -1, 0};
            break;
        case SDL_SCANCODE_SPACE:
            camera.move(cameraSpeed * Vec3f{0, 1, 0});
            //camera.position = camera.position + cameraSpeed * Vec3f{0, 1, 0};
            break;
    }
}
